<?php

namespace App\Http\Controllers\Api;

use App\Models\ZZMed\ZDept;
use App\Models\ZZMed\ZHospMember;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ZZMed\ZPituitaryUserBase;

/**
 *  医生权限-科室授权-地区
 * Class DoctorPermissionController
 * @package App\Http\Controllers\Api
 */
class DoctorPermissionController extends Controller
{


    /**
     *  获取医生的菜单列表
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \App\Exceptions\AuthException
     */
    public function getMenuList()
    {
        $user = $this->authUser();

        $list =  ZHospMember::getMenu($user->id, $user->hosp_id);

        return $this->success($list);
    }

    /**
     *  切换中心获取授权医院科室列表
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \App\Exceptions\AuthException
     */
    public function getAuthorizedDepartmentsUnderHospital(Request $request)
    {
        $doctor = $this->authUser();
        $params = $request->all();
        $type = isset($params["type"]) && $params["type"] = 1 ? 1 : 0;
        return $this->success(ZDept::getAuthorizedDepartments(ZHospMember::getDocDeptId($doctor->id), $type, $doctor->id, 11));
    }

    /**
     *  获取省市区地址
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getLocationDivisions()
    {
        $divisions = ZDept::query()->from('z_location')
            ->where('status', 0)
            ->orderBy('pid', 'desc')
            ->orderBy('id', 'asc')
            ->get()
            ->toArray();;

        $areas = [];
        $lv2Areas = [];
        $lv1Areas = [];
        foreach ($divisions as $division) {
            switch ($division['lv']) {
                case 0:
                    $areas[] = [
                        'id' => $division['id'],
                        'name' => $division['name'],
                        'children' => array_key_exists($division['id'], $lv1Areas) ? $lv1Areas[$division['id']] : []
                    ];
                    break;
                case 1:
                    $lv1Areas[$division['pid']][] = [
                        'id' => $division['id'],
                        'name' => $division['name'],
                        'children' => array_key_exists($division['id'], $lv2Areas) ? $lv2Areas[$division['id']] : []
                    ];
                    break;
                case 2:
                    $lv2Areas[$division['pid']][] = [
                        'id' => $division['id'],
                        'name' => $division['name'],
                    ];
                    break;
                default:
                    break;
            }
        }
        $occupationInfo = ZPituitaryUserBase::query()->where('field_id', 'job')->get()->toArray();
        $areas['occupationInfo'] = $occupationInfo;
        return $this->success($areas);
    }
}
